package org.redis.cluster.admin.registry;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.redis.cluster.config.RegistryConfig;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;

public class ZookeeperRegistry extends org.redis.cluster.registry.zookeeper.ZookeeperRegistry implements InitializingBean {
	
	private final static int DEFAULT_RETRY_COUNT=3;
	
	private Integer retryCount=DEFAULT_RETRY_COUNT;
	
	@Value("${zk.host}")
	private String host;
	@Value("${zk.port}")
	private Integer port;
	@Value("${zk.timeout}")
	private Integer timeout;
	@Value("${zk.root}")
	private String root;
	
	private RegistryConfig config;

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.hasLength(host,"zk.host不能为空");
		Assert.notNull(port,"zk.port不能为空");
		Assert.notNull(timeout,"zk.timeout不能为空");
		Assert.hasLength(root,"zk.root不能为空");
		
		RegistryConfig config=new RegistryConfig();
		config.setHost(host);
		config.setPort(port);
		config.setTimeout(timeout);
		config.setRoot(root);
		
		this.config=config;
		setConfig(config);
		setClient(initClient());
	}
	
	@Override
	protected CuratorFramework initClient() {
		CuratorFramework curatorFramework=CuratorFrameworkFactory.builder()
				.connectString(host)
				.sessionTimeoutMs(timeout)
				.retryPolicy(new RetryNTimes(getRetryCount(),timeout)).build();
		
		curatorFramework.start();
		return curatorFramework;
	}
	
	public void setRetryCount(Integer retryCount) {
		this.retryCount = retryCount;
	}
	public Integer getRetryCount() {
		return retryCount;
	}
	public void setHost(String host) {
		this.host = host;
	}
	public String getHost() {
		return host;
	}
	public void setPort(Integer port) {
		this.port = port;
	}
	public Integer getPort() {
		return port;
	}
	public void setTimeout(Integer timeout) {
		this.timeout = timeout;
	}
	public Integer getTimeout() {
		return timeout;
	}
}